package com.xdap.keymen.service.dayang;

import com.definesys.mpaas.query.MpaasQuery;
import com.xdap.keymen.entity.dayang.*;
import com.xdap.keymen.entity.wm.vo.coupon.UserCoupon;
import com.xdap.keymen.utils.DateTimeUtils;
import com.xdap.keymen.utils.SerialNumberGenerator;
import com.xdap.motor.entity.SnowflakeIdWorker;
import com.xdap.runtime.service.RuntimeAppContextService;
import com.xdap.runtime.service.RuntimeDatasourceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class DaYangCouponDistributionDetailService {
    private final RuntimeDatasourceService runtimeDatasourceService;
    private final RuntimeAppContextService runtimeAppContextService;
    private final SnowflakeIdWorker snowflakeIdWorker;
    private static final String COUPON_STATUS_NOT_USED = "1";
    private static final String COUPON_STATUS_USED = "2";
    private static final String COUPON_STATUS_ABANDON = "3";

    /**
     * 根据储值订单的金额以及匹配的送券模板ID，计算的送券数量，批量发券
     *
     * @param daYangStoreValueOrderEntity 储值订单详情
     * @param daYangCouponEntity          券模板详情
     */
    public DaYangCouponDistributionDetailsEntity buildDistributedCouponsByStoreValueOrder(DaYangStoreValueOrderEntity daYangStoreValueOrderEntity,
                                                                                          DaYangCouponEntity daYangCouponEntity) {
        DaYangCouponDistributionDetailsEntity daYangCouponDistributionDetailsEntity = new DaYangCouponDistributionDetailsEntity();
        //主键ID
        daYangCouponDistributionDetailsEntity.setId(snowflakeIdWorker.nextId());
        daYangCouponDistributionDetailsEntity.setDocumentId(snowflakeIdWorker.nextId());
        daYangCouponDistributionDetailsEntity.setCreatedBy(daYangStoreValueOrderEntity.getCreatedBy());
        daYangCouponDistributionDetailsEntity.setCreationDate(daYangStoreValueOrderEntity.getCreationDate());
        daYangCouponDistributionDetailsEntity.setOwner(daYangStoreValueOrderEntity.getOwner());
        daYangCouponDistributionDetailsEntity.setTenantId(runtimeAppContextService.getCurrentTenantId());
        daYangCouponDistributionDetailsEntity.setLastUpdatedBy(runtimeAppContextService.getCurrentUserId());
        //单据编号
        daYangCouponDistributionDetailsEntity.setDistributionDetailsNumber(generateCouponDistributedNumber());

        //客户编号
        daYangCouponDistributionDetailsEntity.setNameId(daYangStoreValueOrderEntity.getAccountNo());
        //客户名称
        daYangCouponDistributionDetailsEntity.setName(daYangStoreValueOrderEntity.getName());
        //优惠券模板ID
        daYangCouponDistributionDetailsEntity.setTemplateId(daYangStoreValueOrderEntity.getCouponDistribution());
        //赠送时间
        daYangCouponDistributionDetailsEntity.setDistributionTime(new Date());
        //优惠券分类
        daYangCouponDistributionDetailsEntity.setCouponDistributionScenario(daYangCouponEntity.getCouponDistributionScenario());
        //优惠券使用状态(1.未使用，2.已使用，3.已作废)
        daYangCouponDistributionDetailsEntity.setCouponStatus(COUPON_STATUS_NOT_USED);

        //优惠券名称
        daYangCouponDistributionDetailsEntity.setCouponName(daYangCouponEntity.getCouponName());
        //是否过期
        daYangCouponDistributionDetailsEntity.setHasItExpired("1");
        //优惠券面值
        daYangCouponDistributionDetailsEntity.setCouponValue(daYangCouponEntity.getCouponValue());
        //生效日期
        daYangCouponDistributionDetailsEntity.setEffectiveDate(new Date());
        //失效日期
        daYangCouponDistributionDetailsEntity.setExpirationDate(calculateExpiredDate(new Date(), daYangCouponEntity.getValidDays()));
        //有效天数
        daYangCouponDistributionDetailsEntity.setValidDays(daYangCouponEntity.getValidDays());
        //送券场景(优惠券变动场景)
        daYangCouponDistributionDetailsEntity.setCouponDistributeScenario(daYangStoreValueOrderEntity.getCouponDistributionScenario());
        //关联单号
        daYangCouponDistributionDetailsEntity.setOutId(daYangStoreValueOrderEntity.getStoredValueOrderId());
        //优惠券ID
        daYangCouponDistributionDetailsEntity.setCouponId(generateCouponNumber());
        //优惠券类型
        daYangCouponDistributionDetailsEntity.setCouponType(daYangCouponEntity.getCouponType());
        //微盟模板ID
        daYangCouponDistributionDetailsEntity.setWmTemplateId(daYangCouponEntity.getWmTemplateId());
        //不适用门店
        daYangCouponDistributionDetailsEntity.setApplicableStoresNo(daYangCouponEntity.getApplicableStores());
        //赠送原因
        daYangCouponDistributionDetailsEntity.setReason("储值订单赠送");
        daYangCouponDistributionDetailsEntity.setStatus("COMPLETED");
        //满多少可用-券模版中使用门槛
        daYangCouponDistributionDetailsEntity.setMenkan(daYangCouponEntity.getAmountThreshold());
        return daYangCouponDistributionDetailsEntity;
    }

    /**
     * 根据微盟用户的券数据转换得帆的发券
     *
     * @param userCoupon
     * @return
     */
    public DaYangCouponDistributionDetailsEntity buildDistributedCouponsFromWmUserCoupon(UserCoupon userCoupon, DaYangAccountTitleEntity daYangAccountTitleEntity) {
        DaYangCouponDistributionDetailsEntity daYangCouponDistributionDetailsEntity = new DaYangCouponDistributionDetailsEntity();
        //主键ID
        daYangCouponDistributionDetailsEntity.setId(snowflakeIdWorker.nextId());
        daYangCouponDistributionDetailsEntity.setDocumentId(snowflakeIdWorker.nextId());
        daYangCouponDistributionDetailsEntity.setTenantId(runtimeAppContextService.getCurrentTenantId());
        //单据编号
        daYangCouponDistributionDetailsEntity.setDistributionDetailsNumber(generateCouponDistributedNumber());
        //客户编号
        daYangCouponDistributionDetailsEntity.setNameId(daYangAccountTitleEntity.getId());
        //客户名称
        daYangCouponDistributionDetailsEntity.setName(daYangAccountTitleEntity.getName());
        //赠送时间
        daYangCouponDistributionDetailsEntity.setDistributionTime(DateTimeUtils.dateFormat(userCoupon.getPublishTime(), "yyyy-MM-dd hh:mm:ss"));
        //送券场景(送券明细-优惠券-发券场景-change_scenario)
        daYangCouponDistributionDetailsEntity.setCouponDistributeScenario("0");
        daYangCouponDistributionDetailsEntity.setCouponDistributionScenario(getCouponScenarioFromName(userCoupon.getName()));
        //券模板ID
        //daYangCouponDistributionDetailsEntity.setTemplateId();
        //微盟模板ID
        daYangCouponDistributionDetailsEntity.setWmTemplateId(String.valueOf(userCoupon.getCouponTemplateId()));
        //优惠券名称
        daYangCouponDistributionDetailsEntity.setCouponName(userCoupon.getName());
        //是否过期
        daYangCouponDistributionDetailsEntity.setHasItExpired("1");
        //优惠券面值
        daYangCouponDistributionDetailsEntity.setCouponValue(userCoupon.getDiscountAmount());
        daYangCouponDistributionDetailsEntity.setMenkan(userCoupon.getDiscountAmount());
        //生效日期
        Date start = DateTimeUtils.dateFormat(userCoupon.getValidDate().getUseStartTime(), "yyyy-MM-dd hh:mm:ss");
        daYangCouponDistributionDetailsEntity.setEffectiveDate(start);
        //失效日期
        Date end = DateTimeUtils.dateFormat(userCoupon.getValidDate().getUseEndTime(), "yyyy-MM-dd hh:mm:ss");
        daYangCouponDistributionDetailsEntity.setExpirationDate(end);
        //有效天数
        daYangCouponDistributionDetailsEntity.setValidDays(DateTimeUtils.between(start, end));
        //不适用门店
        //daYangCouponDistributionDetailsEntity.setApplicableStoresNo(userCoupon.getExplain());
        //优惠券ID
        daYangCouponDistributionDetailsEntity.setCouponId(generateCouponNumber());
        //优惠券类型
        //默认代金券
        daYangCouponDistributionDetailsEntity.setCouponType("1");
        //赠送原因
        daYangCouponDistributionDetailsEntity.setReason(userCoupon.getExplain());
        //优惠券使用状态(1.未使用，2.已使用，3.已作废)
        daYangCouponDistributionDetailsEntity.setCouponStatus(COUPON_STATUS_NOT_USED);
        daYangCouponDistributionDetailsEntity.setStatus("COMPLETED");
        return daYangCouponDistributionDetailsEntity;
    }

    private String getCouponScenarioFromName(String name) {
        if (name.contains("生日")) {
            return "2";
        } else if (name.contains("存卡")) {
            return "1";
        } else if (name.contains("充")) {
            return "1";
        } else if (name.contains("返图")) {
            return "4";
        } else if (name.contains("转介绍")) {
            return "5";
        } else if (name.contains("储值")) {
            return "1";
        } else {
            return "0";
        }
    }

    /**
     * 批量发券
     *
     * @param distributionDetailsEntities 券列表
     * @return 券信息
     */
    public void distributeCoupons(List<DaYangCouponDistributionDetailsEntity> distributionDetailsEntities) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.doBatchInsert(distributionDetailsEntities);
    }

    /**
     * 获取用户发券详细
     *
     * @param id ID
     * @return 券信息
     */
    public DaYangCouponDistributionDetailsEntity getCouponDetail(String id) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.eq("id", id);
        return query.doQueryFirst(DaYangCouponDistributionDetailsEntity.class);
    }

    /**
     * Update coupon distribution callback.
     *
     * @param couponDistributionDetails {@link DaYangStoredValueRecordEntity}
     * @return Ture or False.
     */
    public Integer updateCouponDistributionDetailsCallback(DaYangCouponDistributionDetailsEntity couponDistributionDetails) {
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.update("up_flag", couponDistributionDetails.getUpFlag());
        query.update("up_error_msg", couponDistributionDetails.getUpErrorMsg());
        query.eq("id", couponDistributionDetails.getId());
        return query.doUpdate(couponDistributionDetails);
    }

    /**
     * 生成送券明细单据编号
     *
     * @return 编号
     */
    public String generateCouponDistributedNumber() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("SQ#");
        stringBuilder.append(DateFormatUtils.format(new Date(), "yyyyMMdd"));
        stringBuilder.append("9");
        stringBuilder.append(SerialNumberGenerator.generateSerialNumber(4));
        return stringBuilder.toString();
    }

    /**
     * 生成券ID
     *
     * @return 编号
     */
    public String generateCouponNumber() {
        //StringBuilder stringBuilder = new StringBuilder();
        //stringBuilder.append(DateFormatUtils.format(new Date(), "yyyy"));
        //获取的优惠券，固定以99开头
        //stringBuilder.append("99");
//        stringBuilder.append(SerialNumberGenerator.generateSerialNumber(8));
        String headStr="99";
        Integer storeNo = 1;
        String currentTenantId = runtimeAppContextService.getCurrentTenantId();
        MpaasQuery query = runtimeDatasourceService.buildTenantMpaasQuery("xdap_app_" + currentTenantId);
        query.sql("select max(right(coupon_id,8))+1 as coupon_id  from dy_coupon_distribution_details");
        DaYangCouponDistributionDetailsEntity entity = query.doQueryFirst(DaYangCouponDistributionDetailsEntity.class);
        if (entity != null) {
            //格式成6位，不足补0
            storeNo = (int) Double.parseDouble(entity.getCouponId());
        }
        return headStr+String.format("%08d", storeNo);
    }

    /**
     * 计算过期时间
     *
     * @return
     */
    public Date calculateExpiredDate(Date effectDate, int validDays) {
        return DateUtils.addDays(effectDate, validDays);
    }

}
